package com.gxc.controller;

import com.gxc.annotation.MyLogAnnotation;
import com.gxc.dao.jpa.UserRepository;
import com.gxc.entity.User;
import com.gxc.service.UserService;
import com.gxc.utils.RestControllerResult;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登陆 Controller.
 *
 * @author 宫新程
 * @since 2018/12/1 3:08 PM
 */
@Controller
public class LoginController {

  @Resource private UserRepository userRepository;
  @Resource private UserService userService;

  /**
   * 登陆校验.
   *
   * @param user 实体类
   * @return Boolean
   */
  @PostMapping("/login")
  @ResponseBody
  //public RestControllerResult<Boolean> login(@RequestBody User user, HttpServletRequest request) {
  public RestControllerResult<Boolean> login(User user, HttpServletRequest request) {
    RestControllerResult<Boolean> result = new RestControllerResult<>();

    List<User> userNameList = userRepository.findByUsername(user.getUsername());
    if (userNameList.isEmpty()) {
      result.setErrorMsg("该用户名不存在！");
      result.setSuccess(false);
      return result;
    }
    User entityUser = userNameList.get(0);
    if (entityUser.getPassword().equals(user.getPassword())) {
      result.setSuccess(true);
      HttpSession session = request.getSession();
      session.setAttribute("login_user", user);
      return result;
    }
    result.setErrorMsg("密码错误！");
    result.setSuccess(false);
    return result;
  }

  /** 退出登陆. */
  @GetMapping("/logout")
  public String logout(HttpServletRequest request) {
    HttpSession session = request.getSession();
    session.invalidate();
    return "redirect: /toLogin";
  }

  /** 用户注册功能. */
  @GetMapping("/register")
  @ResponseBody
  public RestControllerResult<Boolean> register(User user) {
    Boolean date = userService.register(user);
    RestControllerResult<Boolean> result = new RestControllerResult<>();
    result.setData(date);
    result.setSuccess(true);
    return result;
  }
}
